package com.dbh.alg.algorithm.thread;

/**
 * 启动3个线程打印递增的数字，线程1先打印1,2,3,4,5。然后是线程2打印6,7,8,9,10。
 * 然后是线程3打印11,12,13,14,15，接着再由线程1打印16,17,18,19,20......以此类推，直到打印到45。程序的输出结
 */
public class SequentialNumberPrinter {

   private static final int THREAD_COUNT = 3;
   private static final int PRINT_COUNT = 5;
   private static final int MAX_NUMBER = 45;

   private static volatile int currentNumber = 1;
   private static int currentThread = 0;

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(new PrintNumber(i)).start();
        }

    }

    static class PrintNumber implements Runnable {

        private int threadId;

        public PrintNumber(int threadId) {
            this.threadId = threadId;
        }

        @Override
        public void run() {
            while(currentNumber <= MAX_NUMBER) {
                synchronized (SequentialNumberPrinter.class) {
                    while (threadId != currentThread) {
                        try {
                            SequentialNumberPrinter.class.wait();
                        }catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                    for (int i = 0; i < PRINT_COUNT; i++) {
                        System.out.println("线程" + (threadId + 1) + ":" + currentNumber++);
                    }
                    currentThread = (threadId + 1) % THREAD_COUNT;
                    SequentialNumberPrinter.class.notifyAll();
                }
            }
        }
    }

}
